package com.ks.api.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ks.api.entity.KsEventData;
import com.ks.api.service.KsEventDataService;
import com.ks.api.service.KsUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 快手事件数据控制器
 */
@Slf4j
@RestController
@RequestMapping("/event")
@RequiredArgsConstructor
public class KsEventDataController {

    private final KsEventDataService ksEventDataService;
    private final KsUserService ksUserService;
    
    /**
     * 根据用户昵称查询事件数据
     */
    @GetMapping("/search")
    public Map<String, Object> searchEventsByNickname(
            @RequestParam(value = "nickname", required = false) String nickname,
            @RequestParam(value = "nickId", required = false) String nickId,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Map<String, Object> data = ksEventDataService.findEventsByNickname(nickname,nickId, page, size);
            result.put("success", true);
            result.put("data", data);
        } catch (Exception e) {
            log.error("查询事件数据失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 手动触发获取eCPM报表数据
     */
    @GetMapping("/fetch")
    public Map<String, Object> fetchData() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            int count = ksEventDataService.fetchAndSaveEcpmReportData();
            result.put("success", true);
            result.put("count", count);
            result.put("message", "成功获取和保存" + count + "条数据");
        } catch (Exception e) {
            log.error("手动获取eCPM报表数据失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取最近的事件数据列表
     */
    @GetMapping("/recent/{limit}")
    public Map<String, Object> getRecentEvents(@PathVariable("limit") Integer limit) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 限制查询数量，默认最多返回100条
            int queryLimit = limit != null && limit > 0 ? Math.min(limit, 100) : 10;
            
            LambdaQueryWrapper<KsEventData> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.orderByDesc(KsEventData::getCreateTime)
                        .last("LIMIT " + queryLimit);
            
            List<KsEventData> events = ksEventDataService.list(queryWrapper);
            
            result.put("success", true);
            result.put("count", events.size());
            result.put("events", events);
        } catch (Exception e) {
            log.error("获取最近事件数据失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }
    
    /**
     * 获取事件数据统计信息
     */
    @GetMapping("/stats")
    public Map<String, Object> getStats() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取总记录数
            long totalCount = ksEventDataService.count();
            
            // 获取不同事件类型的统计
            LambdaQueryWrapper<KsEventData> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.select(KsEventData::getEventType)
                        .groupBy(KsEventData::getEventType);
            
            List<KsEventData> eventTypes = ksEventDataService.list(queryWrapper);
            
            result.put("success", true);
            result.put("totalCount", totalCount);
            result.put("eventTypes", eventTypes);
            result.put("message", "获取统计信息成功");
        } catch (Exception e) {
            log.error("获取事件数据统计失败", e);
            result.put("success", false);
            result.put("error", e.getMessage());
        }
        
        return result;
    }

    @GetMapping("/all")
    public Map<String, Object> getAllEvents(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) String nickId,
            @RequestParam(required = false) String nickname) {
        return ksEventDataService.findAllEvents(page, size, startTime, endTime, nickId, nickname);
    }

    @PostMapping("/user/ban")
    public Map<String, Object> banUser(@RequestParam String nickId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = ksEventDataService.updateUserStatus(nickId, 0);
            result.put("success", count > 0);
            result.put("message", count > 0 ? "封禁成功" : "封禁失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
        }
        return result;
    }
    
    @PostMapping("/user/unban")
    public Map<String, Object> unbanUser(@RequestParam String nickId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = ksEventDataService.updateUserStatus(nickId, 1);
            result.put("success", count > 0);
            result.put("message", count > 0 ? "解封成功" : "解封失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "操作失败：" + e.getMessage());
        }
        return result;
    }
    
    @PostMapping("/user/settle")
    public Map<String, Object> settleUser(
            @RequestParam String nickId,
            @RequestParam String startTime,
            @RequestParam String endTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            int count = ksEventDataService.updateEventStatus(nickId, startTime, endTime);
            result.put("success", true);
            result.put("message", String.format("成功结算 %d 条记录", count));
            result.put("count", count);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "结算失败：" + e.getMessage());
        }
        return result;
    }
} 